<template>
  <div>
    <basic-container>
      <ele-calendar :render-content="renderContent" @pick="datePickcalendar" @date-change="dateChange"
                    :data="datedef" :prop="prop" :lunarcalendar="true" currentmonth border></ele-calendar>
    </basic-container>

    <el-dialog :visible.sync="dialogTableVisible" width="70%">
      <el-form ref="searchForm" :model="searchForm" label-width="80px" size="mini" >
        <!--<el-col :span="5">
          <el-form-item label="设备状态:">
            <el-select v-model="searchForm.state" placeholder="请选择">
              <el-option label="全部" value="-1"></el-option>
              <el-option v-for="(item) in DIC.TROULBE_STATUS" :key="item.id" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>-->
        <!--<el-col :span="5">
          <el-form-item label="维保类型:">
            <el-select v-model="searchForm.type" placeholder="请选择">
              <el-option label="全部" value="-1"></el-option>
              <el-option v-for="(item) in DIC.TROULBE_STATUS_WB" :key="item.id" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>-->
        <el-col :span="5">
        <el-form-item label="设备类别:">
            <el-cascader v-model="searchForm.equipmentTypeId"
                         :options="equipmentType"
                         :props="{ expandTrigger: 'hover' }"
                         @change="equipmentTypeChange()"></el-cascader>
        </el-form-item>
      </el-col><el-col :span="5">
        <el-form-item label="放置位置:">
          <el-select v-model="searchForm.location" placeholder="请选择">
            <el-option label="全部" value="-1"></el-option>
            <el-option v-for="(item) in DIC.STORAGE_LOCATION" :key="item.id" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
        <el-col :span="14">
          <el-form-item  label-width="20px">
            <el-button type="primary" @click="searchFormSubmit()">搜索</el-button>
            <el-button @click="resetSubmit()">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>

      <avue-crud :option="tableOption" :data="gridData" :table-loading="tableLoading" @size-change='sizeChange'
                 @current-change="currentPage" @selection-change='selectionChange' :page="page" ref="crud" class="customForm" >
        <template slot-scope="scope" slot="menuRight">
          <el-button type="primary" size="small" plain @click.stop="stateModeBtn(2)">维保申请</el-button>
          <el-button type="primary" size="small" plain @click.stop="stateModeBtn(3)">故障报停</el-button>
          <el-button type="primary" size="small" plain @click.stop="stateModeBtn(0)">启用</el-button>
          <el-button type="primary" size="small" plain @click.stop="stateModeBtn(1)">停用</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button type="primary" size="small" plain @click.stop="seeModeBtn(scope.row,scope.index)">台账</el-button>
        </template>
      </avue-crud>
    </el-dialog>
    <!-- 启用/停用 -->
    <el-dialog :visible.sync="stateMode" width="45%" :title="stateModeTitle" center>
      <div v-if="stateMode">
        <el-row>
          <el-col :span="4">设备类别:</el-col>
          <el-col :span="8">{{selectionRow.equipmentTypeName}}</el-col>
          <el-col :span="4">设备编码:</el-col>
          <el-col :span="8">{{selectionRow.coded}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="4">型号:</el-col>
          <el-col :span="8">{{selectionRow.marking}}</el-col>
          <el-col :span="4">品牌:</el-col>
          <el-col :span="8">{{selectionRow.brand}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="4">安装实验室:</el-col>
          <el-col :span="8">{{selectionRow.laboratory == 'null' ? selectionRow.laboratory.name : '' }}</el-col>
          <el-col :span="4">设备名称:</el-col>
          <el-col :span="8"
                  v-if="selectionRow.name">{{selectionRow.name}}</el-col>
        </el-row>
        <!-- 购买价格 -->
        <!-- <el-row v-if="stateModeFormIs ==2">
          <el-row>
            <el-col :span="4">购买价格：</el-col>
            <el-col :span="8">{{selectionRow.marking}}</el-col>
            <el-col :span="4">首次启用时间：</el-col>
            <el-col :span="8">{{selectionRow.brand}}</el-col>
          </el-row>
        </el-row> -->
      </div>
      <!-- 停用 -->
      <el-row v-if="stateModeFormIs==1">
        <el-form ref="stateModeForm"
                 :model="stateModeForm"
                 size="mini">
          <el-form-item label="停用类型："
                        prop="stop_cause"></el-form-item>
          <el-form-item label=""
                        prop="stop_cause">
            <el-radio v-model.number="stateModeForm.stop_cause"
                      :label="0">保养</el-radio>
            <el-radio v-model.number="stateModeForm.stop_cause"
                      :label="1">效准</el-radio>
            <el-radio v-model.number="stateModeForm.stop_cause"
                      :label="2">维修</el-radio>
            <el-radio v-model.number="stateModeForm.stop_cause"
                      :label="3">停用</el-radio>
            <el-radio v-model.number="stateModeForm.stop_cause"
                      :label="4">报废</el-radio>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 维保申请 -->
      <el-row v-if="stateModeFormIs>=2">
        <el-form ref="newspaperStop"
                 :model="newspaperStop"
                 :rules="newspaperStopRules"
                 size="mini">
          <el-form-item :label="newspaperStop.typeTitle"
                        prop="type">
            <el-select v-model="newspaperStop.type"
                       placeholder="请选择">
              <el-option label="请选择"
                         value=""></el-option>
              <el-option label="保养"
                         v-if="stateModeFormIs == 2 || stateModeFormIs == 3"
                         :value="0"></el-option>
              <el-option label="校准"
                         v-if="stateModeFormIs == 2 || stateModeFormIs == 3"
                         :value="1"></el-option>
              <el-option label="维修"
                         v-if="stateModeFormIs == 2 || stateModeFormIs == 3"
                         :value="2"></el-option>
              <!-- 维保 -->
              <el-option v-if="stateModeFormIs == 3"
                         label="报废"
                         :value="3"></el-option>
              <el-option label="停用"
                         v-if="stateModeFormIs == 3"
                         :value="4"></el-option>
              <!-- 报废 -->
              <el-option v-if="stateModeFormIs == 4"
                         label="出售"
                         :value="3"></el-option>
              <el-option label="处理"
                         v-if="stateModeFormIs == 4"
                         :value="4"></el-option>
              <el-option label="其他"
                         v-if="stateModeFormIs == 4"
                         :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="newspaperStop.docsTitle"
                        prop="docs">
            <el-input type="textarea"
                      rows='5'
                      v-model="newspaperStop.docs"></el-input>
          </el-form-item>
        </el-form>
      </el-row>
      <span slot="footer"
            class="dialog-footer">
        <el-button size="small"
                   @click="menuModeFormBtnClose()">关 闭</el-button>
        <el-button size="small"
                   type="primary"
                   @click="menuModeFormBtn()">{{stateModeBtnName}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    import { mapMutations } from 'vuex'
    import eleCalendar from 'ele-calendar'
    import { DIC } from '@/const/dic.js'
    import 'ele-calendar/dist/vue-calendar.css'
    import { option } from "@/const-personal/equipment/aintenance/calendar.js";
    import { getEquipmentType ,
        getEquipmentList ,
        downBack ,
        addMaintenanceAppointment ,
        addTrouble ,
        addScrapApplication ,
        upWalk
    } from '@/api/equipment/device/management.js'
    import { DepartmentTreeVChildrenNull,getDepartmentTreeOfId,formatDate } from "@/util/util.js"
    import { getMaintenanceCalendarList,getMaintenanceCalendarListEquipment } from '@/api/equipment/aintenance/maintenance-application.js'
    import { validatenull } from '@/util/validate'

    export default {
        data(){
            return{
                newspaperStop: { //报废申请
                    type: '',
                    docs: '',
                    typeTitle: '',
                    docsTitle: ''
                },
                newspaperStopRules: {
                    type: [
                        { required: true, message: '请选择类型', trigger: 'change' }
                    ],
                    docs: [
                        { required: true, message: '请输入申请说明', trigger: 'blur' }
                    ]
                },
                selectionRow: { id: '' },
                DIC :DIC,
                tableOption: option, //表格设置属性
                tableData: [], //表格的数据
                tablePage: 1,
                tableLoading: false,
                tabelObj: {},
                page: {
                    total: 0, //总页数
                    currentPage: 1, //当前页数
                    pageSize: 10, //每页显示多少条
                    pageSizes: [5,10,20] //每页显示多少条
                },
                grade: {
                    box: false,
                    check: []
                },
                gridData: [],
                dialogTableVisible: false,
                datedef:[],
                prop:'date', //对应日期字段名,
                searchForm:{//查询表单,
                    state: '-1',
                    type: '-1',
                    equipmentTypeId:['-1'],
                    location: '-1',
                },
                equipmentType:[],
                stateMode: false,//修改状态
                stateModeBtnName: '',//启用模态框按钮名称
                stateModeTitle: '', //启用模态框名称
                stateModeForm: {},//启用模态表单数据
                stateModeFormIs: false,//启用模态框表单启用,
                ids:[]
            }
        },
        components: {
            eleCalendar
        },
        created(){
            this.getComEqType();
            this.getCalenderDate();
        },
        methods: {
            ...mapMutations('equipmentLedger', ['setEquipmentLedger']),
            _successInfo (res, shenqi = false) {
                if (res.data.code === 200) {
                    this.$notify.success(res.data.message)
                    this.handleList();
                    this.stateMode = false
                    this.selectionRow = { id: '' }
                    if (shenqi) {
                        this.$refs['newspaperStop'].resetFields();
                    }
                } else {
                    this.$notify.error(res.data.message)
                }
            },
            currentPage (val) {
                this.page.currentPage = val;
                this.searchFormSubmit();
            },
            sizeChange (val) {
                this.page.pageSize = val
                this.searchFormSubmit()
            },
            selectionChange (selection) {
                this.selectionRow = selection[selection.length - 1] || { id: '' }
            },
            seeModeBtn (row, index) {
                this.setEquipmentLedger(row)
                this.$router.push({
                    path: this.$router.$avueRouter.getPath({
                        name: '1设置',
                        src: '/ledger/equipmentLedger'
                    }),
                    query: { id: row.id }
                });
            },
            stateModeBtn (state) {
                if (!this.selectionRow.id) {
                    this.$notify.info('请选择你需要操作的项目')
                    return;
                }
                const stateBtnName = ['启用', '停用', '提交', '提交', '提交']
                const stateTitle = ['启用确认', '停用确认', '维保申请单', '故障报停单', '报废申请单']
                this.stateMode = true;
                this.stateModeBtnName = stateBtnName[state]
                this.stateModeTitle = stateTitle[state]
                this.stateModeFormIs = state; //停用
                if (state >= 2) {
                    this.newspaperStop.typeTitle = stateTitle[state].slice(0, 2) + '类型'
                    this.newspaperStop.docsTitle = stateTitle[state].slice(0, 2) + '说明'
                }
            },
            getCalenderDate(){
                this.getDataList(formatDate(new Date(),'yyyy-MM-dd'))
            },
            dateChange(data){
                this.getDataList(formatDate(data,'yyyy-MM-dd'))
            },
            datePickcalendar(date, event, row, dome) {
                this.ids = row.value.ids
                this.searchFormSubmit();
            },
            getDataList(date){
                getMaintenanceCalendarList({
                    date :date
                }).then(res=>{
                    res.data.data.forEach(item=>{
                        if(item.maintainCount !=0 || item.correctCount !=0){
                            this.datedef.push({'date': item.date, 'content': '  保养：'+ item.maintainCount +'              校准： '+ item.correctCount, "ids": item.ids})
                        }
                    })
                })
            },
            // 设备类别
            comEqType () {
                return ((type) => {
                    for (let i = 0; i < this.equipmentType.length; i++) {
                        if (this.equipmentType[i].id == type) {
                            // console.log("name:" + this.equipmentType[i].label)
                            return this.equipmentType[i].label
                        }
                    }
                })
            },
            resetSubmit(){
                this.searchForm = {
                    state: '-1',
                    type: '-1',
                    equipmentTypeId:['-1'],
                    location: '-1',
                }
            },
            searchFormSubmit(){
                if(validatenull(this.ids)){
                    return null;
                }
                let data = {
                    state: this.searchForm.state == '-1' ? null : this.searchForm.state,
                    type: this.searchForm.type == '-1' ? null : this.searchForm.type,
                    ids: this.ids,
                    equipmentTypeId: this.searchForm.equipmentTypeId[length] == '-1' ? null : this.searchForm.equipmentTypeId[length],
                    page: this.page.currentPage,
                    size: this.page.pageSize,
                }
                this.tableLoading = true
                getMaintenanceCalendarListEquipment(data)
                    .then(res => {
                        if (res.data.code === 200) {
                            const data = res.data.data;
                            this.gridData = data.list;
                            this.gridData.forEach(item=> {
                                item.equipmentTypeName = getDepartmentTreeOfId(this.equipmentType, item.equipmentTypeId).label;
                                item.webao = item.maintainCycle + ' / '+ item.correctCycle +  ' / '+ item.maintainWaring ;
                                item.update = item.updateName + ' / '+ item.updateName;
                            })
                            this.page.total = data.total;
                            this.page.pageSize = data.pageSize
                            this.page.currentPage = data.pageNum
                            this.tableLoading = false;
                        } else {
                            this.$notify.error(res.data.message)
                        }
                    });
            },
            getComEqType () { // 设备类别
                getEquipmentType().then(res => {
                    if (res.data.code === 200) {
                        this.equipmentType = DepartmentTreeVChildrenNull(res.data.data,[{label:'全部',value:'-1'}])
                    } else {
                        this.$notify.error({ title: '查询失败', message: res.data.message, type: 'danger', });
                    }
                })
            },
            renderContent(h,parmas) {
                const loop = data =>{
                    return data.defvalue.value ? h('div', [
                            h('span', { style: {marginRight: '30px'},}, data.defvalue.Lunar.lDayChinese),
                            h('span', data.defvalue.text),
                            h('div', [
                                h('span', {
                                    props: {  style: 'lunarcalendarValue' },
                                    on: { click: () => { this.dialogTableVisible = true; }}
                                }, data.defvalue.value.content)
                            ])
                        ]):
                        h('div', [
                            h('span', { style: {marginRight: '30px'},}, data.defvalue.Lunar.lDayChinese),
                            h('span', data.defvalue.text)
                        ]);
                }
                return (
                    <div  class='lunarcalendarClass'>
                    {loop(parmas)}
                    </div>
                );
            },
            menuModeFormBtnClose(){
                this.stateMode = false;
            },
            menuModeFormBtn () {
                const state = this.stateModeFormIs //操作按钮
                const { id } = this.selectionRow
                if (state === 0) {//启用
                    //选择项id
                    upWalk({ id }).then(res => {
                        this._successInfo(res)
                    })
                } else if (state === 1) {//停用
                    if (this.stateModeForm.stop_cause === '') {
                        this.$notify.info('请选择停用类型')
                        return;
                    }
                    let params = {
                        id,
                        stopCause: this.stateModeForm.stop_cause
                    }
                    console.log(params);
                    downBack(params).then(res => this._successInfo(res))
                } else {
                    this.$refs['newspaperStop'].validate(valid => {
                        // console.log(v, 'v');
                        if (valid) {
                            if (state === 2) { //维保申请
                                let params = {
                                    // equipmentId: id,
                                    // maintenanceType: this.newspaperStop.type,
                                    // maintenanceInstructions: this.newspaperStop.docs
                                    equipmentId: id,
                                    maintenanceType: this.newspaperStop.type,
                                    remakes: this.newspaperStop.docs
                                    // applicationTime: this.formatDate() //申请时间（取得本地时间）
                                }
                                console.log(params, '维保申请');
                                addMaintenanceAppointment(params).then(res => this._successInfo(res, true))
                            } else if (state === 3) { // 故障报停
                                let params = {
                                    equipmentId: id,
                                    troubleStatus: this.newspaperStop.type,
                                    troubleNote: this.newspaperStop.docs
                                }
                                addTrouble(params).then(res => this._successInfo(res, true))
                            } else if (state === 4) { //报废申请
                                let params = {
                                    equipmentId: id,
                                    // scrapStatus: this.newspaperStop.type,
                                    scrapType: this.newspaperStop.type,
                                    maintenanceInstructions: this.newspaperStop.docs
                                }
                                addScrapApplication(params).then(res => this._successInfo(res, true))
                            }
                        } else {
                            this.$notify.info('请填写信息')
                            return false;
                        }
                    })
                }
            },
        }
    }
</script>
<style>
  .lunarcalendarClass{
    min-height:70px;
  }
  .lunarcalendarClass>div>div>span{
    border: 1px solid #409EFF;
    background-color: #409EFF;
    color: #FFFFFF;
    padding: 2px 25px;
    border-radius: 5px;
  }
  .customForm .avue-crud__menu{
    width: 70%;
    float: right;
    display: inline-block;
  }
  .customForm .avue-crud__right{
    float:right;
  }
  .customForm .avue-crud__right button{
    margin-right: 0px!important;
    margin-left: 8px!important;
  }
  .customForm .avue-crud__tip{
    margin: 0px;
  }
</style>